<?php
/*
# $Id$
#
# Sends out all emails stored in the "email" db table.
*/

use Buan\ModelCriteria;
use Buan\ModelManager;
use Buan\SystemLog;

// Init
if(!defined('CRON')) {
	die("Cannot execute this script directly.");
}

// Load all unsent emails
$c = new ModelCriteria();
$c->addClause(ModelCriteria::EQUALS, 'datesent', 0);
$c->addOrder('datecreated');
$emails = ModelManager::select('ScribbleMail', $c);
foreach($emails as $email) {

	// Send mail
	try {
		$success = $email->sendNow();
		$email->logMessage("Message was sent to {$success} recipient(s)");

		if($success==0) {
			$email->logMessage("Failed to send message");
			SystemLog::add(array('Failed to send email #%s.', $email->id));
		}
		else {
			$email->datesent = time();
			$email->logMessage("Mail sent successfully");
			if(!$email->getModelManager()->save($email)) {
				SystemLog::add(array('Failed to save email #%s after a successful send.', $email->id));
				continue;
			}
		}
	}
	catch(Swift_ConnectionException $e) {
		$email->logMessage($e->getMessage());
		SystemLog::add(array("Email #%s: ".$e->getMessage(), $email->id));
		continue;
	}
}
?>